package com.lonty.intelligence.service;

import com.github.qcloudsms.SmsMultiSenderResult;
import com.lonty.intelligence.api.Result;
import com.lonty.intelligence.api.ResultCode;
import com.lonty.intelligence.mapper.UserInfoMapper;
import com.lonty.intelligence.model.UserInfo;
import com.lonty.intelligence.request.CommitteeIdAndNameList;
import com.lonty.intelligence.request.UserInfoAndCommunityList;
import com.lonty.intelligence.util.*;
import com.lonty.intelligence.vo.UserInfoVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author 陈璇
 * @Date 2020/4/16 10:43
 * @Version 1.0
 **/
@Service
public class UserInfoService {

    @Resource
    private UserInfoMapper userInfoMapper;

    /**
     * 根据Id获取用户信息
     * @param id
     * @return
     */
    public UserInfoAndCommunityList getById(String id){
        return userInfoMapper.getById(id);
    }

    /**
     * 用户登录
     * @param userInfoVo
     * @return
     */
    @Transactional
    public Map<String,Object> login(UserInfoVo userInfoVo) throws Exception {
        UserInfoAndCommunityList getUser = null;
        //获取微信登录返回的对象信息
        String openid = WeChatUtil.weChatLogin(userInfoVo.getCode());
        Map<String,Object> map = new HashMap<>();
        //判断登录类型  0:小程序登录 1:手机登录
        if(userInfoVo.getLoginType().equals(0)){
            if(StringUtils.isEmpty(openid)){
                map.put("code",101);
                map.put("msg","微信登录失败");
                return map;
            }
            getUser = userInfoMapper.getByOpenId(openid);
        }else{
            getUser = userInfoMapper.getByTelephone(userInfoVo.getTelephone());
        }
        //判断用户是否是新用户
        if(getUser == null){
            getUser = new UserInfoAndCommunityList();
            BeanUtils.copyProperties(userInfoVo,getUser);
            getUser.setId(UUIDUtil.randomID());
            getUser.setToken(UUIDUtil.randomUUID());
            getUser.setEdition("1.0.0");
            getUser.setOpenid(openid);
            getUser.setIdentity(0);
            getUser.setType(0);
            getUser.setIsRealName(0);
            getUser.setIsDel(0);
            getUser.setRoleId(1);
            UserInfo userInfo = new UserInfo();
            BeanUtils.copyProperties(getUser,userInfo);
            userInfoMapper.saveUserInfo(userInfo);
        }else{
            UserInfoAndCommunityList userInfo = userInfoMapper.getById(getUser.getId());
            BeanUtils.copyProperties(getUser,userInfo);
            userInfoMapper.modifyUserInfo(userInfo);
            getUser = userInfoMapper.getById(getUser.getId());
        }
        map.put("getUser",getUser);
        return map;
    }

    /**
     * 发送验证码, 过期时间五分钟
     * @param phone
     * @return
     */
    public Result sendMessage(String phone){
        //生成六位验证码
        String code = IntegerUtils.random();
        //把验证码存入redis
        boolean result = RedisUtil.set(phone, code, RedisUtil.DEFAULT_EXPIRE);
        if(!result){
            return Result.builder(ResultCode.OPERATION_ERROR).build();
        }
        //发送验证码
        SmsMultiSenderResult senderResult = MessageUtil.sendMessage(phone, code);
        //发送失败
        if (senderResult.result != 0) {
            return Result.builder(ResultCode.OPERATION_ERROR).build();
        }
        return Result.builder().build();
    }

    /**
     * 绑定手机号
     * @param userInfoId
     * @param phone
     * @param code
     * @return
     */
    @Transactional
    public Result bindingMobilePhone(String userInfoId, String phone, String code){
        String verificationCode = (String) RedisUtil.get(phone);
        if(verificationCode == null){
            //验证码已过期
            return Result.builder(ResultCode.CODE_IS_OVERDUE).build();
        }
        //判断验证码是否正确
        if(!code.equals(verificationCode)){
            return Result.builder(ResultCode.CODE_IS_ERROR).build();
        }
        //根据手机号获取用户信息
        UserInfoAndCommunityList userInfo = userInfoMapper.getByTelephone(phone);
        //如果用户信息不为空则为居委、房主和住户, 修改身份和手机号, 删除只有手机号的姓名的信息  如果为空则绑定手机号
        if(userInfo != null){
            if(userInfo.getIdentity().equals(1)){
                //为居委
                userInfoMapper.authenticationInformation(userInfoId, phone, userInfo.getCommunityId(), userInfo.getRealName());
            }
            userInfoMapper.deleteUserInfo(userInfo.getId());
        }else{
            userInfoMapper.modifyTelephone(userInfoId, phone);
        }
        //返回新的用户信息
        userInfo = userInfoMapper.getById(userInfoId);
        return Result.builder().data(userInfo).build();
    }

    /**
     * 保存居委成员
     * @param name
     * @param telephone
     * @return
     */
    public boolean saveCommittee(String name, String telephone, String communityId){
        //根据手机号获取用户信息
        UserInfoAndCommunityList userInfo = userInfoMapper.getByTelephone(telephone);
        //根据手机号判断用户信息是否存在, 存在则修改身份, 不存在则新增
        if(userInfo != null){
            return userInfoMapper.authenticationInformation(userInfo.getId(), telephone, communityId, name) > 0;
        }else{
            return userInfoMapper.saveCommittee(UUIDUtil.randomID(), name, telephone, communityId) > 0;
        }
    }

    /**
     * 根据社区ID获取居委ID、名称
     * @param communityId
     * @return
     */
    public List<CommitteeIdAndNameList> getCommitteeIdAndName(String communityId){
        return userInfoMapper.getCommitteeIdAndName(communityId);
    }

    /**
     * 根据ID修改手机号和真实姓名
     * @param id
     * @param telephone
     * @param realName
     * @return
     */
    public boolean updateTelephoneAndRealName(String id, String telephone, String realName){
        return userInfoMapper.updateTelephoneAndRealNameAndType(id, telephone, realName, null) > 0;
    }

}
